<!--
*   Coder : Dzlua
*   Email : 505544956@qq.com
*   Time  : 2017/08/30
-->
{% extends "bootstrap/base.html" %}
{% block title %}Flasky{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle"data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">Dzlua</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="/tools">Tools</a></li>
            </ul>
        </div>
    </div>
</div>
{% endblock %}
{% block content %}
<div class="container">
    <form id="form1" role="form" onsubmit="return submitFrom();">
        <div class="input-group">
            <div class="input-group-btn">
                <select id="method1" class="form-control" style="width: 100px;" onchange="selectMethod(this);">
                    <option>GET</option>
                    <option selected>POST</option>
                </select>
            </div><!-- /btn-group -->
            
            <input id="addr1" type="text" class="form-control" placeholder="请输入请求地址"/>

            <div class="input-group-btn">
                <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" tabindex="-1">
                        <span class="caret"></span>
                        <span class="sr-only">切换下拉菜单</span>
                </button>
                <ul class="dropdown-menu pull-right">
                    <li><a onclick="selectApiAddress(this);" name="method:POST;param:word;">词典-> http://dict-co.iciba.com/search.php</a></li>
                    <li><a onclick="selectApiAddress(this);" name="method:POST;data:from,to,query;">翻译-> http://fanyi.baidu.com/v2transapi</a></li>
                    <li><a onclick="selectApiAddress(this);" name="method:POST;data:username,password;">注册-> http://127.0.0.1:1507/api/register</a></li>
                    <li><a onclick="selectApiAddress(this);" name="method:POST;">Token-> http://127.0.0.1:1507/api/token</a></li>
                    <li><a onclick="selectApiAddress(this);" name="method:POST;data:userid;">用户-> http://127.0.0.1:1507/api/get_user</a></li>
                    <li><a onclick="selectApiAddress(this);" name="method:POST;">users-> http://127.0.0.1:1507/api/users</a></li>
                    <li><a onclick="selectApiAddress(this);" name="method:POST;data:libname,content,pagecount;">SO-> http://127.0.0.1:1507/api/so</a></li>
                    <li><a onclick="selectApiAddress(this);" name="method:GET;header:header;param:param;data:data;">Dir-> http://127.0.0.1:1507/api/dir</a></li>
                </ul>
                <button id="btn1" type="submit" class="btn btn-default">发送请求</button>
            </div>
        </div><!-- /input-group -->

        <br/>

        <div class="panel panel-info">
            <div class="panel-heading">
                <h4 class="panel-title">
                    <a data-toggle="collapse" data-parent="#accordion" href="#collapse_basic_auth">认证</a>
                </h4>
            </div>
            <div id="collapse_basic_auth" class="panel-collapse collapse">
                <div class="panel-body">
                    <table class="table table-hover" id="table_basic_auth"></table>
                </div>
            </div>
        </div>

        <div class="panel panel-info">
            <div class="panel-heading">
                <h4 class="panel-title">
                    <a data-toggle="collapse" data-parent="#accordion" href="#collapse_header">请求头</a>
                </h4>
            </div>
            <div id="collapse_header" class="panel-collapse collapse">
                <div class="panel-body">
                    <table class="table table-hover" id="table_req_header"></table>
                </div>
            </div>
        </div>
    
        <div class="panel panel-info">
            <div class="panel-heading">
                <h4 class="panel-title">
                    <a data-toggle="collapse" data-parent="#accordion" href="#collapse_param">请求参数</a>
                </h4>
            </div>
            <div id="collapse_param" class="panel-collapse collapse">
                <div class="panel-body">
                    <table class="table table-hover" id="table_req_param"></table>
                </div>
            </div>
        </div>
    
        <div id="div_body" class="panel panel-info">
            <div class="panel-heading">
                <h4 class="panel-title">
                    <a data-toggle="collapse" data-parent="#accordion" href="#collapse_body">请求Body</a>
                </h4>
            </div>
            <div id="collapse_body" class="panel-collapse collapse">
                <div class="panel-body">
                    <ul class="nav nav-tabs">
                        <li class="active"><a href="#body_form" data-toggle="tab">Form</a></li>
                        <li><a href="#body_string" data-toggle="tab">String</a></li>
                    </ul>
                    <div class="tab-content">
                        <br/>
                        <div class="tab-pane fade in active" id="body_form">
                            <table class="table table-hover" id="table_req_body_form"></table>
                        </div>
                        <div class="tab-pane fade" id="body_string">
                            <textarea id="text_body_string" class="form-control" onkeyup="MaxTextarea(this);" style="overflow: hidden;resize:none"></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    
        <div class="panel panel-info">
            <div class="panel-heading">
                <h4 class="panel-title">
                    <a data-toggle="collapse" data-parent="#accordion" href="#collapse_response">响应</a>
                </h4>
            </div>
            <div id="collapse_response" class="panel-collapse collapse in">
                <div class="panel-body">
                    <ul class="nav nav-tabs">
                        <li class="active"><a href="#res_show" data-toggle="tab">Show</a></li>
                        <li><a href="#res_code" data-toggle="tab">Code</a></li>
                        <li><a href="#res_detail" data-toggle="tab">Details</a></li>
                    </ul>
                    <div class="tab-content">
                        <br/>
                        <div class="tab-pane fade in active" id="res_show"></div>
                        <div class="tab-pane fade" id="res_code"><pre id="res_code_code"></pre></div>
                        <div class="tab-pane fade" id="res_detail"><pre id="res_detail_code"></pre></div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script type="text/javascript">
    /**
    * param 将要转为URL参数字符串的对象
    * key URL参数字符串的前缀
    * encode true/false 是否进行URL编码,默认为true
    * 
    * return URL参数字符串
    */
    var urlEncode = function (param, key, encode) {
        if(param==null) return '';
        var paramStr = '';
        var t = typeof (param);
        if (t == 'string' || t == 'number' || t == 'boolean') {
            paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);
        } else {
            for (var i in param) {
                var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
                paramStr += urlEncode(param[i], k, encode);
            }
        }
        return paramStr;
    };

    /*
    * 自动增高 textarea
    */
    function MaxTextarea(o) {     
        if (window.navigator.userAgent.indexOf("Firefox") > -1) {
            o.style.height = o.scrollTop + o.scrollHeight + "px";
        }
        else {
            if (o.scrollTop > 0) o.style.height = o.scrollTop + o.scrollHeight + "px";
        }
    }

    function selectMethod(o) {
        return;
        if (o.value=='POST') {
            document.getElementById('div_body').style.display="inline";
        } else if (o.value=='GET') {
            document.getElementById('div_body').style.display="none";
        }
    }

    /*
    * a href click, 输入api地址
    */
    function selectApiAddress(o) {
        function parser_param_data(str) {
            var pos = str.indexOf(':');
            var t = str.substr(0, pos);
            var d = str.substr(pos + ':'.length);
            var ds = d.split(',');
            var datas = {};
            for (var i=0; i< ds.length; ++i) {
                datas[ds[i]] = '';
            }
            return [t, datas];
        }

        function parser_param(str) {
            var strs = str.split(';');
            if (strs[0]) {
                document.getElementById('method1').value = strs[0].split(':')[1];
            }

            for (var i=1; i<strs.length; i++) {
                if (!strs[i]) break;
                var [t,datas] = parser_param_data(strs[i]);
                
                if (t=='param') {
                    add_tr_param(datas, true);
                } else if (t=='data') {
                    add_tr_body_form(datas, true);
                } else if (t=='header') {
                    add_tr_header(datas, true);
                }
            }
        }

        clear_all();
        parser_param(o.name);
        //
        var str = '-> ';
        var text = o.innerText;
        var pos = text.indexOf(str) + str.length;
        text = text.substr(pos);
        document.getElementById('addr1').value = text;
    }

    /*
    * 提交表单
    */
    function submitFrom() {
        document.getElementById('res_show').innerHTML = '';
        document.getElementById('res_code_code').innerText = '';
        document.getElementById('res_detail_code').innerText = '';
        //
        function auth_and_header() {
            var headers = get_req_header();
            var auths = get_req_basic_auth();
            // 只使用第一个
            for (var key in auths) {
                headers['Authorization'] = 'Basic ' + btoa(key + ':' + auths[key]);
                break;
            }
            return headers;
        }
        //
        var datas = {
            method: document.getElementById('method1').value,
            action: document.getElementById('addr1').value,
            headers: auth_and_header(),
            params: get_req_param(),
            datas: get_req_body(),
        };

        if (datas.action == '') {
            alert('请输入请求地址!');
            return false;
        }

        $.ajax({
            type: 'POST',
            url: "{{url_for('api_req', _external=True)}}",
            data: datas,
            error: function(xhr, textStatus, errorThrown) {
                alert('error');
                alert(JSON.stringify(xhr));
                document.getElementById('res_show').innerHTML = xhr.responseText;
                document.getElementById('res_code_code').innerText = xhr.responseText;
                document.getElementById('res_detail_code').innerText = JSON.stringify(xhr, null, 4);
            },
            success: function(data, status, xhr) {
                var text = 'Request: \n';
                text += JSON.stringify(data.req, null, 4) + '\n';
    
                text += '-----------------\n';
                text += 'Response: \n';
                text += JSON.stringify(data.res, null, 4) + '\n';

                try{
                    document.getElementById('res_show').innerHTML = '<pre>' + JSON.stringify(JSON.parse(data.res.text), null, 4) + '</pre>';
                } catch (e) {
                    document.getElementById('res_show').innerHTML = data.res.text;
                }
                try{
                    document.getElementById('res_code_code').innerText = JSON.stringify(JSON.parse(data.res.text), null, 4);
                } catch (e) {
                    document.getElementById('res_code_code').innerText = data.res.text;
                }
                document.getElementById('res_detail_code').innerText = text;
            }
        });

        return false;
    }

    /*
    * 初始化table的内容
    * id: table的id
    * trs: 初始化 trs 行
    */
    function init_table(id, trs = 1, allow_value_empty=false) {
        function add_tr(tb, key='', value='') {
            var tbody = tb.getElementsByTagName('tbody')[0];
            var tr = document.createElement('tr');
            tr.innerHTML = '<td><input type="text" class="form-control"/></td><td><input type="text" class="form-control"</td><td><button type="button" class="btn btn-default btn-sm">删除</button></td>';
            tbody.appendChild(tr);
            var btn = tr.getElementsByTagName('td')[2].getElementsByTagName('button')[0];
            btn.addEventListener('click', function() {
                tbody.removeChild(this.parentNode.parentNode);
            });
            tr.getElementsByTagName('td')[0].getElementsByTagName('input')[0].value = key;
            tr.getElementsByTagName('td')[1].getElementsByTagName('input')[0].value = value;
        }
        //
        var tb = document.getElementById(id);
        tb.innerHTML = '<thead><tr><th>KEY</th><th>VALUE</th><th><button type="button" class="btn btn-default btn-sm">添加</button></th></tr></thead><tbody></tbody>';
        //
        var add_btn = tb.getElementsByTagName('thead')[0].getElementsByTagName('th')[2].getElementsByTagName('button')[0];
        add_btn.addEventListener('click', function() {
            add_tr(tb);
        });
        //
        for(var i=0; i<trs; ++i)
            add_tr(tb);

        return [function () {
            var datas = {};
            var tbody = tb.getElementsByTagName('tbody')[0];
            var trs = tbody.getElementsByTagName('tr');
            for(var i=0; i<trs.length; ++i) {
                var tds = trs[i].getElementsByTagName('td');
                var key = tds[0].getElementsByTagName('input')[0].value
                var value = tds[1].getElementsByTagName('input')[0].value
                if(key && key!='') {
                    if (allow_value_empty || (value && key!='') )
                        datas[key] = value;
                }
            }
            return datas;
        }, function(datas, clear=false) {
            if (clear) {
                var tbody = tb.getElementsByTagName('tbody')[0];
                tbody.innerHTML = '';
            }
            var badded = false;
            for (var key in datas) {
                add_tr(tb, key, datas[key]);
                badded = true;
            }

            if (!badded && clear) {
                add_tr(tb);
            }
        }];
    }

    // 初始化4个table，返回获取内容的函数
    var [get_req_basic_auth, add_tr_basic_auth] = init_table('table_basic_auth', 1,true);
    var [get_req_header, add_tr_header] = init_table('table_req_header');
    var [get_req_param, add_tr_param] = init_table('table_req_param');
    var [get_req_body_form, add_tr_body_form] = init_table('table_req_body_form');

    // 获取body的内容
    function get_req_body() {
        var form = get_req_body_form();
        var data = document.getElementById('text_body_string').value;
        return data=='' ? form : data;
    }

    // 清空所有
    function clear_all() {
        document.getElementById('addr1').innerHTML = '';
        //
        add_tr_basic_auth(null, true);
        add_tr_header(null, true);
        add_tr_param(null, true);
        add_tr_body_form(null, true);
        document.getElementById('text_body_string').innerHTML = '';
        //
        document.getElementById('res_show').innerHTML = '';
        document.getElementById('res_code_code').innerText = '';
        document.getElementById('res_detail_code').innerText = '';
    }

</script>

{% endblock %}